package org.yray.sip.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.yray.sip.factory.inet.IStopWatchFactory;
import org.yray.sip.server.SipSession;

@Slf4j
@Component
public class StopWatchFactory implements IStopWatchFactory {

    public final static String TASK_183_A="TASK_183_A";
    public final static String TASK_200_A="TASK_200_A";
    public final static String TASK_200_B="TASK_200_B";
    public final static String TASK_RTP_RECEIVER_A="TASK_RTP_RECEIVER_A";
    public final static String TASK_RTP_RECEIVER_B="TASK_RTP_RECEIVER_B";
    public final static String TASK_ACTION_INVITE="TASK_ACTION_INVITE";
    public final static String TASK_ACTION_ACTIVE_BYE="TASK_ACTION_ACTIVE_BYE";
    public final static String TASK_ACTION_ACTIVE_CANCEL="TASK_ACTION_ACTIVE_CANCEL";
    public final static String TASK_ACTION_TOMAN="TASK_ACTION_TOMAN";
    @Override
    public void begin(SipSession sipSession) {
        sipSession.getStopWatch().start(TASK_ACTION_INVITE);
    }

    @Override
    public void periodStart(SipSession sipSession, String periodName) {
        if(!sipSession.getStopWatch().isRunning()) {
            log.error("periodStart,callid={},sipSession,begin={},it's not running",sipSession.getCallId(), sipSession.getBeginTime());
            return;
        }
        sipSession.getStopWatch().stop();
        sipSession.getStopWatch().start(periodName);
    }

    @Override
    public void end(SipSession sipSession) {
        if(!sipSession.getStopWatch().isRunning()) {
            log.error("periodStart,callid={},sipSession,begin={},it's not running",sipSession.getCallId(), sipSession.getBeginTime());
            return;
        }
        sipSession.getStopWatch().stop();
    }

    @Override
    public String info(SipSession sipSession) {
        StopWatch stopWatch=sipSession.getStopWatch();
        StringBuilder sb=new StringBuilder();
        sb.append("[totalSecond=").append(stopWatch.getTotalTimeSeconds());
        for(StopWatch.TaskInfo info:stopWatch.getTaskInfo())
        {
            sb.append(",taskName=").append(info.getTaskName()).append(",second=").append(info.getTimeSeconds());
        }
        sb.append("]");
       return sb.toString();
    }
}
